package cn.itcast.caomao.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.itcast.caomao.dto.CaoqiuGoodsList;
import cn.itcast.caomao.dto.CaoqiuOrder;
import cn.itcast.caomao.dto.CaoqiuSnthesisOrder;
import cn.itcast.caomao.dto.CaoqiuResult;
import cn.itcast.controller.IpBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.Proxy;
import java.util.*;

/**
 * 昆仑
 */
@RestController
@Slf4j
public class CaoqiuController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    public  static volatile Map<String,IpBean> ret=new HashMap<>();
    @RequestMapping("/createCmsynthesis")
    public String createCmsynthesis(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                                 @RequestParam(value = "id",defaultValue = "24") String id) {
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int z=0;z<tokenList.size();z++){
                    Proxy proxy=null;
                    int finalZ = z;
                    ThreadUtil.execAsync(() -> {
                        confireCmsynthesis(proxy,tokenList.get(finalZ),id);
                    });
//                    confireCmsynthesis(proxy,tokenList.get(finalZ),id);
//                    Thread.sleep(1000);
//                    confireCmsynthesis(proxy,tokenList.get(z),id);

                }
                Thread.sleep(6000);

            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####草球执行完成#####");
        return null;
    }
    private void confireCmsynthesis(Proxy proxy, String token, String id) {
        String result=null;
        try{
            Map<String,String> ret=new HashMap<>();
            ret.put("id",id);
            result = HttpRequest.post("https://h5.caoqiu.vip/synthetic/synthetic").formStr(ret).header("Token",token)
                    .setReadTimeout(5000)
                    .execute().body();
        }catch (Exception e){
            log.info("####合成订单异常######"+e.getMessage()+"####"+result);
        }
        if(!StringUtils.isEmpty(result)){
            log.info("######合成订单异常#######"+token+"##合成id###"+result);
            CaoqiuResult
                    caoqiuResult= JSONUtil.toBean(result, CaoqiuResult.class);
            if(caoqiuResult.getCode()==1){
                log.info("######合成订单成功#######"+token+"######"+caoqiuResult.getMsg());
            }else{
                log.info("######合成订单失败#######"+token+"######"+caoqiuResult.getMsg());
            }
        }else{
            log.info("##获取商品数据异常##");
        }
    }

    @RequestMapping("/createCmMarket")
    public String createCmMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                    for(int z=0;z<tokenList.size();z++){
                        Proxy proxy=null;
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1000);
                    }

            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####草球执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品数据异常####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        String result=null;
        try{
            Long time=System.currentTimeMillis();
            Map<String,String> ret=new HashMap<>();
            ret.put("page","1");
            ret.put("goods_id",goodsId);
            ret.put("sort_type","3");
            result = HttpRequest.post("https://h5.caoqiu.vip/sale/getMarketGoodsList").formStr(ret)
                    .setReadTimeout(5000)
                    .execute().body();
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(!StringUtils.isEmpty(result)){
            CaoqiuGoodsList
                    caoqiuGoodsList= JSONUtil.toBean(result, CaoqiuGoodsList.class);
            log.info("######获取商品数据成功#######"+caoqiuGoodsList.toString()+"##商品id###"+goodsId);
            if(caoqiuGoodsList.getData()!=null && !CollectionUtils.isEmpty(caoqiuGoodsList.getData().getData())){
                List<CaoqiuGoodsList.CaoqiuGoodsDetailList> list=caoqiuGoodsList.getData().getData();
                for(CaoqiuGoodsList.CaoqiuGoodsDetailList detailDTO:list){
                    if(new BigDecimal(detailDTO.getGoods_price()).compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
//                        ThreadUtil.execAsync(() -> {
//                            saveOrder(finalProxy,token,detailDTO,goodsId);
//                        });
                        saveOrder(finalProxy,token,detailDTO,goodsId);
                        Thread.sleep(1100);
                    }

                }
            }
        }else{
            log.info("##获取商品数据异常##");
        }
    }

    public void saveOrder(Proxy proxy, String token,CaoqiuGoodsList.CaoqiuGoodsDetailList detailDTO,String goodsId){

        String createResult=null;
        try {
            Map<String,String> ret=new HashMap<>();
            ret.put("goods_id",goodsId);
            ret.put("order_type","3");
            ret.put("id",detailDTO.getId());
            createResult =
                    HttpRequest.post("https://h5.caoqiu.vip/order/createOrder").formStr(ret).header("Token",token).execute().body();
            CaoqiuOrder caoqiuOrder= JSONUtil.toBean(createResult, CaoqiuOrder.class);
            log.info("####支付结果######"+caoqiuOrder.toString());
            if(caoqiuOrder!=null && caoqiuOrder.getCode() ==1){
                MailUtil.send("1027060531@qq.com", "草球支付", "您有一个草球的订单，请赶紧支付！", false);
                ret.clear();
                ret.put("order_id",caoqiuOrder.getData().getOrderId());
                ret.put("pay_type","5");
                ret.put("pwd","");
                ret.put("random_key","");
                ret.put("card_id","0");
                ret.put("operation_pwd","891223");
                //支付订单
                createResult =
                        HttpRequest.post("https://h5.caoqiu.vip/member/toPay").formStr(ret).header("Token",token).execute().body();
                caoqiuOrder= JSONUtil.toBean(createResult, CaoqiuOrder.class);
                if(caoqiuOrder!=null && caoqiuOrder.getCode()==1){
                    MailUtil.send("1027060531@qq.com", "草球支付", "艾斯您有一个昆仑新的订单，请赶紧支付！", false);
                }
                log.info("####支付结果######"+caoqiuOrder.toString());
            }
        } catch (Exception e) {
            log.info("####支付结果异常######"+e.getMessage()+":detailDTO"+detailDTO.toString());
        }
    }
    public void addToken(){
        //15182211372
//        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjQ5NTMzNSwibmJmIjoxNjg2NDk1MzM1LCJleHAiOjE2ODY1ODE3MzUsIm1lbWJlcl9pbmZvIjo0Njc5NH0.SCQIG0rTfAXJ3kcl42le4WhNfIfKRh8GwvpdbHZTwJE");
        //15689276016
//        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjQ5NTM3MSwibmJmIjoxNjg2NDk1MzcxLCJleHAiOjE2ODY1ODE3NzEsIm1lbWJlcl9pbmZvIjo0NjM0N30.gugK3Z3Qoim700eotxcPuUBGbWgIUmy0rnSEbsvVySU");
        //13151506052
//        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjQ5NTQwMSwibmJmIjoxNjg2NDk1NDAxLCJleHAiOjE2ODY1ODE4MDEsIm1lbWJlcl9pbmZvIjo0NjM1MX0.Y3aL_Eps8CwazORaLNIQaPsRiSzOGNo2yMS5Pb9Qw9s");
        //13803993919
//        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjQ4NjkxMywibmJmIjoxNjg2NDg2OTEzLCJleHAiOjE2ODY1NzMzMTMsIm1lbWJlcl9pbmZvIjo0NjM0OX0.c84jUZyXrGA5UGOty3cZcY_Jb-VBGL_g0vsSbuEKwOg");
//        //18883759475
//        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjQ5NTQzMCwibmJmIjoxNjg2NDk1NDMwLCJleHAiOjE2ODY1ODE4MzAsIm1lbWJlcl9pbmZvIjo0NjM0Nn0.IK2uXkvjdrsKN_AycUxowcFXcyZvYwUfzvxDxgd6J7Q");
        //13996955613
        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjQ5NTQ3MCwibmJmIjoxNjg2NDk1NDcwLCJleHAiOjE2ODY1ODE4NzAsIm1lbWJlcl9pbmZvIjo0NjM0NH0.lwurfczCmLiOHwX4bbZFBI871Iq-C2tCqMa6eQqoZxY");
    }

}
